import axios from 'axios'
import { useUserStore } from '@/stores/user'
import {Message} from "@arco-design/web-vue";

const $http = axios.create({
    baseURL: import.meta.env.VITE_API_URL,
    timeout: 15000
})

// 请求拦截器（处理租户ID和token）
$http.interceptors.request.use(config => {
    const userStore = useUserStore()

    console.log('nickName = ', userStore.userInfo?.username)

    config.headers['X-Tenant-Id'] = userStore.tenantId
    config.headers['X-User-Id'] = userStore.userId
    config.headers['X-User-Name'] = `${userStore.userInfo?.username}`
    config.headers['satoken'] = `Bearer ${userStore.token}`
    // 添加设备信息
    config.headers['X-Client-Info'] = navigator.userAgent
    return config
})

// 响应拦截器（处理401等状态）
$http.interceptors.response.use(
    response => {
        const res = response.data
        if (res.code !== 200) {
            Message.warning(res.msg || '服务器端发生异常！')
            return Promise.reject(res)
        }
        return res
    },
    error => {
        Message.error(error.msg || '服务器连接失败')
        return Promise.reject(error)
    }
)
export default $http